<template>
  <div class="app-container">
    <el-form :model="form" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="成品" prop="productId">
        <el-select
          v-model="form.productId"
          placeholder="请选择成品"
          clearable
          :style="{width: '100%'}" :disabled="this.$route.query.id!=null">
          <el-option
            v-for="(item, index) in productList"
            :key="index"
            :label="item.productName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item><br>
      <el-form-item label="状态" prop="status" v-if="this.$route.query.id">
        <div>
          <span>{{ form.product.status==0 ? '下架' : (this.form.product.status==1 ? '上架' : '停产')}}</span>
        </div>
      </el-form-item><br>
      <el-form-item label="操作人" prop="createBy" v-if="this.$route.query.id">
        <div>
          <span>{{ form.createBy }}</span>
        </div>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime" v-if="this.$route.query.id">
        <div>
          <span>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-left: 20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomItemList" height="500" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编号" align="left" prop="material.materialCode" />
      <el-table-column label="物料名称" align="left" prop="material.materialName" >
        <template slot-scope="scope">
          <el-autocomplete
            class="inline-input"
            v-model="scope.row.material.materialName"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect(scope.row,$event)"
          >
            <template slot-scope="{ item }">
              <span>{{ item.materialName }}</span>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column label="物料类型" align="left" prop="material.materialType" >
        <template slot-scope="scope">
          <span>{{ scope.row.material.materialType == 1 ? "原材料" : scope.row.material.materialType == 2 ? "半成品" : scope.row.material.materialType == 3 ? "成品": "辅料" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="left" prop="material.specification" />
      <el-table-column label="类型" align="left" prop="material.categoryName" />
      <el-table-column label="数量" align="left" prop="quantity" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.quantity" />
        </template>
      </el-table-column>
      <el-table-column label="标准单价" align="left" prop="material.standardPrice" />
      <el-table-column label="备注" prop="remark" align="center"  width="120">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" />
        </template>
      </el-table-column>
    </el-table>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.remark" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom } from "@/api/system/Bom";
import { listMaterial } from "@/api/system/Material";
import { listProduct } from "@/api/system/Product";
import {parseTime} from "../../../utils/ruoyi";

export default {
  name: "orderAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      payTypes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品下拉框
      productList: [],
      //销售出库单详情表格数据
      bomItemList: [],
      // 物料框
      restaurants: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
        salerName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },
      //物料清单表ID数据
      bomAllList:[],
      //物料清单详情表ID数据
      bomItemDetailAllList:[],
    };
  },
  created() {
    this.getList();
    this.getMaterialtList();
  },
  methods: {
    parseTime,
    /** 查询订单详情 */
    getList() {
      this.loading = false;
      this.bomItemDetailAllList=[];
      listBom().then(response => {
        this.bomItemDetailAllList = response.rows;
        console.log(this.bomItemDetailAllList)
        let list=response.rows;
        for (var i=0;i<list.length;i++){
          this.bomAllList.push(list[i].id);
        }
      });
      listProduct().then(response => {
        this.productList = response.rows;
      })
      if (this.$route.query.id!=null){
        this.selectOrder(this.$route.query.id);
      }
    },
    /** 查询订单详情 */
    selectOrder(id) {
      getBom(id).then(response => {
        // 订单赋值
        this.form = response.data;
        this.bomItemList = response.data.bomItemList;
      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.materialName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 物料列表
    getMaterialtList() {
      listMaterial().then(response => {
        this.restaurants = response.rows;
        console.log(this.restaurants)
      });
    },
    // 物料下拉选中
    handleSelect(row, item) {
      for (let i = 0; i < this.bomItemList.length; i++) {
        if (this.bomItemList[i].material.materialName === item.materialName){
          this.$modal.msgError("商品已存在");
          this.bomItemList[this.bomItemList.length-1].material = {
            id: null,
            materialName: null,
            materialCode: null,
            materialType: null,
            specification: null,
            categoryName: null,
            standardPrice: null,
          };
          this.bomItemList[this.bomItemList.length-1].quantity = 0;
          this.bomItemList[this.bomItemList.length-1].remark = '';
          return;
        }
      }
      row.material = item;
      console.log(item)
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    // 物料框
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.code ? [row.code] : this.ids;
      this.$modal.confirm('是否确认删除该物料列表？').then(() => {
        this.bomItemList = this.bomItemList.filter(product => !ids.includes(product.id));
        this.handleSelectionChange([]); // 清空选中项
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 物料新增按钮操作 */
    handleAdd() {
      if (this.form.productId == null || this.form.productId === ''){
        this.$modal.msgError("请先选择成品");
        return;
      }
      const id = generateUniqueId(this.bomItemDetailAllList);
      // 添加一个新的空商品对象到商品列表中
      this.bomItemList.push({
        id: id,
        material: {
          id: null,
          materialName: null,
          materialCode: null,
          materialType: null,
          specification: null,
          categoryName: null,
          standardPrice: null,
        },
        quantity: 0,
        sort: this.bomItemList.length + 1,
        remark: null
      });
    },
    /** 提交按钮 */
    submitForm() {
      for (let i = 0; i < this.bomItemList.length; i++) {
        if (this.bomItemList[i].quantity <= 0){
          this.$modal.msgError("数量不能小于0");
          return;
        }
      }
      if (this.$route.query.id) {
        this.form.bomItemList=this.bomItemList;
        updateBom(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      }else{
        const newId = generateUniqueId(this.bomAllList);
        var orderCode = getOrderCode(this.bomItemDetailAllList);
        this.form.id=newId;
        this.form.code=orderCode;
        for (let i = 0; i < this.bomItemList.length; i++) {
          this.bomItemList[i].bomId=newId;
          this.bomItemList[i].materialId=this.bomItemList[i].material.id;
          this.bomItemList[i].lossRate = 10;  //损耗率
        }
        this.form.bomItemList=this.bomItemList;
        this.form.createBy="系统管理员";
        this.form.updateBy="系统管理员";
        this.form.status=0;

        console.log(this.form);
        addBom(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      }
    }
  },
  //  路由离开
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.oo = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="WLQD";  //物料清单
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      console.log(list[i])
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
